package com.suncmf.demo.controller;

import com.suncmf.demo.domain.AuthRole;
import com.suncmf.demo.model.RoleModel;
import com.suncmf.demo.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.util.List;

@RestController
public class RoleController {


    @Autowired
    private RoleService roleService;

    @RequestMapping(value = "/role/{id}", method = RequestMethod.GET)
    public AuthRole findById(@PathVariable int id){


        return roleService.findById(id);
    }

    @RequestMapping(value = "/role/save", method = RequestMethod.POST)
    public int saveRole( @ModelAttribute @Valid RoleModel roleModel,
                         BindingResult bindingResult){

        if (bindingResult.hasErrors()) {

            List<ObjectError> errorList = bindingResult.getAllErrors();
            for(ObjectError error : errorList){
                System.out.println(error.getDefaultMessage());
            }
            return bindingResult.getErrorCount();
        }

        AuthRole authRole1 = new AuthRole();

        authRole1.setCode("role_test");
//        authRole1.setName("测试角色");
        Short roleStatus = 0;
        authRole1.setStatus(roleStatus);

        int result = roleService.save(authRole1);

        return authRole1.getId();
    }

    @RequestMapping(value = "/role/update", method = RequestMethod.POST)
    public int updateRole() {

        AuthRole authRole = new AuthRole();

        authRole.setId(126);
        authRole.setCode("role_test126");
        authRole.setName("测试角色126111");
        Short roleStatus = 0;
        authRole.setStatus(roleStatus);

        int result = roleService.save(authRole);

        return result;
    }

    @RequestMapping(value = "/role/delete", method = RequestMethod.POST)
    public int deleteRole() {

        int result = roleService.forceDeleteById(126);

        return result;
    }

}
